#! /usr/bin/env python
# encoding: utf-8

from DB.sql_tool import msql_executemany,msql_select
from constants import config_obj,out,err,warn,debug
from parser_data import xml_to_tup
import traceback
import json



#filterwarnings('error', category = pymysql.Warning)


#def show_china(s):
#    print json.dumps(s, indent = 2,ensure_ascii = False)



class InsertMysql(object):
    """docstring for InsertMysql"""
    # def __init__(self, tablename):
    #     self.tablename = tablename
    #     # self.col = col
    #     # self.data = data


    def sql_(self,table_name,columns_name):
        columns = ", ".join(columns_name)
        add1 = "%s, "*len(columns_name)
        debug("len of col :{}".format(len(columns_name)))
        add1 = add1.rstrip(", ")
        debug("len of add :{}".format(len(add1)))
        sql = "INSERT IGNORE INTO {} ({}) VALUES ({})".format(table_name,columns,add1)
        print sql
        return sql


    def insert_(self,sql,data):
        try:
            result = msql_executemany(sql,data)
            return result
        except:
            warn(traceback.format_exc())


    def conv_(self,data):
        return [data]


    def main_sql(self,tablename,xml_data):
        try:
                data, title = xml_to_tup(xml_data)
                if len(data) > 0:
                        data = self.conv_(data)
                        sql = self.sql_(tablename,title)
                        debug(sql)
                        debug("len of data:{}".format(len(data)))
                        result = self.insert_(sql,data)
                        out("插入数据{}条")
                else:
                        out('无数据:  {}表'.format(tablename))
        except:
                err(traceback.format_exc())





# if __name__ == '__main__':
#     InsertMysql('emr.v_home_page','2019-01-01','2019-01-02').main_()
